import {
  SET_TABBAR_SHOW,
  ADD_COUNTER,
  ADD_TO_CART,
  CLEAR_CART_LIST,
  SET_CART_LIST
} from "./types";

export default {
  // 设置tabbar显示和隐藏
  [SET_TABBAR_SHOW](state, isShow) {
    state.tabBarShow = isShow;
  },
  // 同一个商品增加数量
  [ADD_COUNTER](state, payload) {
    payload.count++;
    localStorage.setItem("cartList", JSON.stringify(state.cartList));
  },
  // 给购物车添加商品
  [ADD_TO_CART](state, payload) {
    payload.count = 1;
    payload.checked = false;
    state.cartList.push(payload);
    localStorage.setItem("cartList", JSON.stringify(state.cartList));
  },
  // 清空购物车
  [CLEAR_CART_LIST](state) {
    // 取出未选中的商品重新赋值
    let res = state.cartList.filter(item => !item.checked);
    if(res.length === 0) {
      state.cartList = [];
      localStorage.removeItem("cartList");
    } else {
      state.cartList = res;
      localStorage.setItem("cartList", JSON.stringify(state.cartList));
    }
  },
  // 从LocalStorage中取出购物车信息重新赋值
  [SET_CART_LIST](state, data) {
    state.cartList = data;
  }
}